package ncc.bs.Plugins;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.gl.diffanalynode.diffanalynodehead.IDiffanalynodeVOService;
import nc.itf.pub.dbservice.IDBService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.bcbd.abstractmaterial.AbstractMaterialVO;
import nc.vo.bcbd.bcengine.BDBarCodeParseVO;
import nc.vo.gl.differenceanalysis.DiffanalynodeBVO;
import nc.vo.gl.differenceanalysis.DiffanalynodeVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nccloud.bs.log.LogVO;
import nccloud.dto.gl.lightgl.VoucherQueryVO;
import nccloud.utils.baseapp.HttpReqUtils;
import nccloud.utils.baseapp.InitParamUtils;
import nccloud.utils.baseapp.ToolUtils;

/**
 * <p>同步财政系统</p>
  * 单位会计盈余与结余差异表
 * @author Administrator
 * @date 2024年03月05日
 */
public class DWKJYUAndJYBackgroundWorkPlugin extends AbstractBackgroundWorkPlugin {
	private BaseDAO dao;
	private final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat ymdsfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private IDBService dbService;

	@SuppressWarnings("rawtypes")
	@Override
	public void doBusiness(Map keyMap) throws BusinessException {
		VoucherQueryVO queryVO = buildQueryVO(keyMap);
		IDiffanalynodeVOService service = NCLocator.getInstance().lookup(IDiffanalynodeVOService.class);
		try {
			String message = null;
			String issuccess = "Y";
			String result = null;
			DiffanalynodeVO[] vos = service.queryWithVoucherQueryVO(queryVO);
			if(vos == null) {
				getLog().info("---当前区间【"+keyMap.get("begindate").toString().substring(0,7)+"】不存在差异数据:" + keyMap);
				return;
			}
            JSONArray data = new JSONArray();
			for (DiffanalynodeVO vo : vos) {
				data.add(buildData(vo));
			}
			JSONArray[] arrs = this.splitJSONArray(data, 50);
			for(JSONArray arr : arrs) {
				String param = super.getParam(arr, "DWKJHS09", super.getAppid()); // 每十行数据合并在一起推送
				if (param == null || "".equals(param)) return;
				result = HttpReqUtils.sendPost(getURL("DEF001"), param);
				getLog().info("----第四步接口响应结果::" + result);
				JSONObject jsonres = JSONObject.parseObject(result);
				Object code = jsonres.get ("code");
				if ("200".equals(code)) {
					message = "同步成功";
				} else {
					message = jsonres.getString("msg");
					issuccess = "N";
					result = jsonres.toString();
				}
			}

		} catch (Exception e) {
			LogVO vo = new LogVO();
			vo.setPk_id(NCLocator.getInstance().lookup(IdGenerator.class).generate());
			vo.setIssuccess("N");
			vo.setPk_group("0001A210000000000JB9");
			vo.setPk_billtypeid("dwkjYYAndJY");
			vo.setSystem_flag("financial");
			vo.setVdef1("拉取参数、类型:" + keyMap.get("type") + ",开始日期:" + keyMap.get("begindate") + "结束日期:" + keyMap.get("enddate") + ",同步频率:" + keyMap.get("synctime"));
			vo.setError("单位帐套同步:" + e.getMessage());
			getDbService().insertVO(vo);
		}
	}
	protected JSONArray[] splitJSONArray(JSONArray original, int chunkSize) {
		int originalSize = original.size();
		int arrayCount = (int) Math.ceil((double) originalSize / chunkSize);
		JSONArray[] splitArrays = new JSONArray[arrayCount];

		for (int i = 0; i < arrayCount; i++) {
			int start = i * chunkSize;
			int end = Math.min(start + chunkSize, originalSize);
			splitArrays[i] = new JSONArray();
			for (int j = start; j < end; j++) {
				splitArrays[i].add(original.get(j));
			}
		}

		return splitArrays;
	}
	/**
	 * 获取第三方同步地址
	 *
	 * @param initCode
	 * @return
	 * @throws Exception
	 */
	public String getURL(String initCode) throws Exception {
		String url = InitParamUtils.getOrgParam("GLOBLE00000000000000", initCode) + "/pty/gla-dec/v1/voucher/voudiffs";
		getLog().info("----第三步接口请求地址:" + url);
		return url;
	}

	/**
	 * 数据库操作服务
	 *
	 * @return
	 */
	public IDBService getDbService() {
		if (dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}

	/**
	 * 构建差异分析查询条件
	 *
	 * @param keyMap
	 * @return
	 * @throws BusinessException
	 */
	public VoucherQueryVO buildQueryVO(Map keyMap) throws BusinessException {
		VoucherQueryVO queryVO = new VoucherQueryVO();
		queryVO.setAppcode("20023730");
		Object startdate = null;
		Object stopdate = null;
		Object type = keyMap.get("type");
		if ("1".equals(type)) { //  [指定时间段拉取,1];[拉指定的一天,2];
			Object begindate = keyMap.get("begindate") == null ? ymd.format(new Date()) : keyMap.get("begindate");
			Object enddate = keyMap.get("enddate") == null ? ymd.format(new Date()) : keyMap.get("enddate");
			startdate = begindate + " 00:00:00";
			stopdate = enddate + " 23:59:59";
		} else if ("2".equals(type)) { // [拉指定的一天,2]
			Object begindate = keyMap.get("begindate") == null ? ymd.format(new Date()) : keyMap.get("begindate");
			startdate = begindate + " 00:00:00";
			stopdate = begindate + " 23:59:59";
		} else { // [定时执行, ] 默认同步频率30分钟
			Calendar calendar = Calendar.getInstance();
			stopdate = ymdsfm.format(calendar.getTime());//当前时间
			Object synctime = keyMap.get("synctime"); //  同步频率
			if (synctime == null) {
				calendar.add(Calendar.MINUTE, -30); // time 的前几分钟
			} else {
				int time = Integer.parseInt(synctime.toString());
				calendar.add(Calendar.MINUTE, -time); // time 的前几分钟
			}
			startdate = ymdsfm.format(calendar.getTime());
		}
		Object orgCode = keyMap.get("org");
		List<Object> accountbooks = new ArrayList<Object>();
		if (orgCode == null || "".equals(orgCode)) {
			Object pk_org = getDao().executeQuery("select pk_accountingbook from org_accountingbook where dr = 0 and code = '00101-0002'", new ColumnProcessor());
			accountbooks.add(pk_org);
		} else {
			Object pk_org = getDao().executeQuery("select pk_accountingbook from org_accountingbook where dr = 0 and code = '"+orgCode+"-0002' ", new ColumnProcessor());
			accountbooks.add(pk_org);
		}
		queryVO.setPk_accountingbook(accountbooks.toArray(new String[accountbooks.size()]));
		queryVO.setPeriod(new String[]{});
		queryVO.setYear_start(startdate.toString().substring(0, 4));
		queryVO.setYear_end(stopdate.toString().substring(0, 4));
		queryVO.setPeriod_start(startdate.toString().substring(5, 7));
		queryVO.setPeriod_end(stopdate.toString().substring(5, 7));
		queryVO.setNormalflag(UFBoolean.FALSE.booleanValue());
		queryVO.setDiscardflag(UFBoolean.FALSE.booleanValue());
		queryVO.setTempsaveflag(UFBoolean.FALSE.booleanValue());
		queryVO.setErrorflag(UFBoolean.FALSE.booleanValue());
		queryVO.setDifftype("2");
		queryVO.setIncludeNotAccounted(UFBoolean.FALSE.booleanValue());
		queryVO.setOffervoucher("0");
		return queryVO;
	}
	/**
	 * 构建请求参数
	 * @return
	 * @throws Exception 
	 */
	private JSONObject buildData(DiffanalynodeVO vo) throws Exception{
		JSONObject json = new JSONObject();
		String pk_voucher = vo.getPk_voucher();
		IDiffanalynodeVOService voucherService = NCLocator.getInstance().lookup(IDiffanalynodeVOService.class);
		DiffanalynodeBVO[] diffanalynodeBVOS = voucherService.queryBodyWithPkVoucher(pk_voucher);
		if(diffanalynodeBVOS != null){
			String sql = "select gl_voucher.adjustperiod,gl_voucher.num,gl_voucher.period,gl_voucher.year,pk_org,pk_group,pk_org_v from gl_voucher where pk_voucher = '" + pk_voucher + "'";
			Map<String, Object> maps = (Map<String, Object>)this.getDao().executeQuery(sql, new MapProcessor());
			for (DiffanalynodeBVO diffvo : diffanalynodeBVOS) {
				diffvo.getPk_detial();
				json.put("DIFF_ID", UUID.randomUUID().toString());
				json.put("VOU_ID", diffvo.getPk_voucher());
				json.put("MOF_DIV_CODE", super.getMOF_DIV_CODE());
				json.put("VOU_DET_ID", diffvo.getPk_detial());
				json.put("AGENCY_CODE", super.getUnit()); //单位代码
				json.put("ACCT_SET_NAME", super.getACCT_SET_NAME());  // 账套名称
				json.put("AGENCY_NAME", super.getAGENCY_NAME()); // 单位名称
				json.put("SET_YEAR", maps.get("year")); //会计年度
				json.put("ACCT_SET_CODE", super.getAccount());
				json.put("ACCT_PERIOD", ToolUtils.getJudgeAttribute(maps.get("adjustperiod"))); //
				json.put("VOUCHER_NO", ToolUtils.getJudgeAttribute(maps.get("num"))); //
				json.put("DIFF_TYPE_CODE", diffvo.getAccsubjname().substring(0, diffvo.getAccsubjname().indexOf("\\")));
				json.put("DIFF_AMT", diffvo.getAttributeValue("diffamount").toString());
				json.put("CREATE_TIME", super.getYMDHMS(vo.getCreationtime()));
				json.put("UPDATE_TIME", super.getYMDHMS(vo.getModifiedtime()));
				json.put("VOUCHER_DATE", super.getYMDHMS(vo.getModifiedtime()));
				json.put("IS_DELETED", 2); // 1已删除 2 未删除
				Map<String, Object> map = new HashMap<>();
				map.put("pk_group",maps.get("pk_group"));
				map.put("pk_org",maps.get("pk_org"));
				map.put("pk_org_v",maps.get("pk_org_v"));
				map.put("pk_billtypeid","cyfx");
				LogVO logVO = getDbService().buildLogVO(map, json, "financial", "dwkjYYAndJY");

			}

		}
		return json;
	}
	
	public BaseDAO getDao() {
		return dao == null ? new BaseDAO() : dao ;
	}

}
